package handler

import (
	db "echo_prj/db"
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/labstack/echo"
)

//获取新闻
func GetNews(c echo.Context) error {
	var a = Res{}

	page := c.FormValue("page")
	limit := c.FormValue("limit")

	pageNum, err := strconv.Atoi(page)
	limitNum, err := strconv.Atoi(limit)
	if err != nil {
		log.Println("GetNews,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}

	as, err := db.GetNews(pageNum, limitNum)
	if err != nil {
		log.Println("GetNews,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: as,
		}
	}
	return c.JSON(200, a)
}

//获取单条新闻
func GetNewsDetail(c echo.Context) error {
	var a = Res{}
	id := c.FormValue("id")
	idNum, err := strconv.Atoi(id)
	if err != nil {
		log.Println("GetNewsDetail,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}

	as, err := db.GetNewsDetail(idNum)
	if err != nil {
		log.Println("GetNewsDetail,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: as,
		}
	}
	return c.JSON(200, a)
}

//发布新闻
func PostNews(c echo.Context) error {
	title := c.FormValue("title")
	abstract := c.FormValue("abstract")
	content := c.FormValue("content")
	contentText := c.FormValue("text")
	coverId := c.FormValue("coverId")
	isTop := c.FormValue("isTop")
	releaseDate := time.Now().Format("2006-01-02 15:04:05")
	textImgs := c.FormValue("textImgs")
	id, err := db.PostNews(title, abstract, content, contentText, coverId, isTop, releaseDate, textImgs)
	var a = Res{}
	if err != nil {
		log.Println("PostNews", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: id,
		}
	}
	return c.JSON(200, a)
}

//修改新闻
func EditNews(c echo.Context) error {
	var a = Res{}
	title := c.FormValue("title")
	abstract := c.FormValue("abstract")
	content := c.FormValue("content")
	contentText := c.FormValue("text")
	coverId := c.FormValue("coverId")
	isTop := c.FormValue("isTop")
	uid := c.FormValue("id")
	textImgs := c.FormValue("textImgs")

	id, err := db.EditNews(title, abstract, content, contentText, coverId, isTop, uid, textImgs)
	if err != nil {
		log.Println("EditNews,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: id,
		}
	}
	return c.JSON(200, a)
}

//删除新闻
func DelNews(c echo.Context) error {
	var a = Res{}

	uid, err := strconv.Atoi(c.FormValue("id"))
	if err != nil {
		log.Println("DelNews,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}

	id, err := db.DelNews(fmt.Sprint(uid))
	/* err1 := os.Remove("./view/"+path)
	if  err1 != nil{
		fmt.Println(err1)
	} */

	if err != nil {
		log.Println("DelNews,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: id,
		}
	}
	return c.JSON(200, a)
}
